from PIL import Image, ImageOps, ImageFilter

# 透明度转换 素描转换的一部分
def dodge(a, b, alpha):
    # alpha为图片透明度
    return min(int(a * 255 / (256 - b * alpha)), 255)

# 图片转换为素描
def toSketchStyle(picturePath, blur=25, alpha=1.0):
    # 设置输入输出路径和文件名称
    imgInput_FileName = picturePath
    imgOutput_FileName = picturePath.split(".")[0] + '_Sketch.' + picturePath.split(".")[1]

    # 转化成ima对象
    img = Image.open(picturePath)
    # 将文件转成灰色
    img1 = img.convert('L')

    img2 = img1.copy()

    img2 = ImageOps.invert(img2)

    # 模糊度
    for i in range(blur):
        img2 = img2.filter(ImageFilter.BLUR)
    width, height = img1.size
    for x in range(width):
        for y in range(height):
            a = img1.getpixel((x, y))
            b = img2.getpixel((x, y))
            img1.putpixel((x, y), dodge(a, b, alpha))

    # 保存转换后文件
    img1.save(imgOutput_FileName)
    return '文件转换成漫画成功，保存在' + imgOutput_FileName